package main

import (
	"fmt"
	"github.com/ethereum/go-ethereum/accounts/keystore"
	"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/google/uuid"
)

var privateKey = "0x45c418fbe5c252381bf1699d348362d12fc560c01f1be3dd9c576e6e6475caf6"

// 319d00d5b18831f68618babc024ad995df2aa7f5
func main() {
	key, _ := KeyStore(privateKey, "my secret")
	fmt.Println("keystore:", key)
	priKey := decode([]byte(key), "my secret")
	fmt.Println("private key:", priKey)
}

func KeyStore(prikey, auth string) (string, error) {
	private, _ := crypto.HexToECDSA(prikey[2:])

	key := &keystore.Key{
		Id:         uuid.New(),
		Address:    crypto.PubkeyToAddress(private.PublicKey),
		PrivateKey: private,
	}

	keyjson, err := keystore.EncryptKey(key, auth, keystore.LightScryptN, keystore.LightScryptP)
	return string(keyjson), err
}

func decode(json []byte, auth string) string {
	key, _ := keystore.DecryptKey(json, auth)
	return hexutil.Encode(crypto.FromECDSA(key.PrivateKey))
}
